import * as echarts from 'echarts'
import React, { useEffect, useRef } from 'react'

let option = {
    grid: {
        left: '3%',
        right: '0%',
        top: '10%',
        bottom: '10%',
        width: '97%',
        height: '80%',
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow',
            shadowStyle: {
                color: 'rgba(220,207,181, 0.3)',
            },
            lable: {
                color: '#fff',
            },
        },
        textStyle: {
            color: 'rgba(255,255,255,0.85)',
            fontSize: '9px',
        },
        backgroundColor: '#000',
        borderColor: '#000',
        formatter: (data: any) => {
            return `人数：${data[0].value}人`
        },
    },
    xAxis: {
        type: 'category',
        axisTick: {
            show: false,
        },
        data: ['0-100', '101-200', '201-300', '301-400', '401-500', '501-600', '601-700', '701-800', '801-900', '901-1000'],
    },
    yAxis: {
        type: 'value',
        max: 30,
        splitLine: {
            lineStyle: {
                color: '#ece8d1',
            },
        },
    },
}

export default function Bar({ data, id }: { data: number[]; id: string }) {
    const chartRef = useRef<any>({ chart: null })
    useEffect(() => {
        let chartDom = document.getElementById(id)
        let myChart = echarts.init(chartDom as HTMLElement)
        chartRef.current.chart = myChart

        myChart.setOption({
            ...option,
            series: [
                {
                    data: data.map(item => {
                        return {
                            value: item,
                            label: {
                                position: 'right',
                            },
                            itemStyle: {
                                color: '#935A2F',
                            },
                        }
                    }),
                    barWidth: 42,
                    type: 'bar',
                },
            ],
        })
    }, [])

    useEffect(() => {
        chartRef.current.chart &&
            chartRef.current.chart.setOption({
                ...option,
                series: [
                    {
                        data: data.map(item => {
                            return {
                                value: item,
                                label: {
                                    position: 'right',
                                },
                                itemStyle: {
                                    color: '#935A2F',
                                },
                            }
                        }),
                        type: 'bar',
                    },
                ],
            })
    }, [data])

    return <div style={{ height: '2rem', width: '100%' }} id={id} />
}
